package org.smartboot.compare.comparator;

import org.smartboot.compare.ComparatorContext;
import org.smartboot.compare.ComparatorRegister;
import org.smartboot.compare.Option;
import org.smartboot.compare.difference.Difference;
import org.smartboot.compare.difference.BaseDifference;
import org.smartboot.compare.utils.ComparatorUtils;

import java.util.Objects;

/**
 * @author qinluo
 * @version 1.0.0
 * @since 2019-05-27 16:53
 */
public class StringComparator extends AbstractComparator<String> {

    @Override
    public Difference compare(String expect, String actual, ComparatorContext<String> context) {
        if (context.hasOption(Option.LOOSE_MODE) && ComparatorUtils.checkEmpty(expect, actual)) {
            return Difference.SAME;
        }

        Object newExpect = context.getFeatureFunction().convertString2Object(context, expect);
        Object newActual = context.getFeatureFunction().convertString2Object(context, actual);

        if (newExpect != null && newActual != null
                && newActual != actual && newExpect != expect) {
            ComparatorContext<Object> newCtx = context.clone(newExpect, newActual);
            return ComparatorRegister.dispatcherComparator().compare(newCtx);
        }

        if (!Objects.equals(expect, actual)) {
            return new BaseDifference(context.getPath(), expect, actual);
        }

        return Difference.SAME;
    }
}

